﻿using Share;
using UnityEngine;

public class AudioOneShot : AudioBase
{
    private AudioSource audioSource;
    private AudioClip currentClip;

    protected void Awake()
    {
        audioSource = AudioManager.AddAudioSource(gameObject);
        audioSource.playOnAwake = false;
        audioSource.loop = false;
    }

    public void Play(AudioClip clip)
    {
        if (IsPlaying(clip)) return;
        ReleaseCurrentClip();
        audioSource.PlayOneShot(ObjectPoolManager.Instance.GetFreeAudioClipFromPool(clip), Volume);
    }
    public void Play(string clipName)
    {
        if (IsPlaying(clipName)) return;

        ReleaseCurrentClip();

        currentClip = ObjectMgr.Instance.CreateAudioClip(clipName);
        audioSource.PlayOneShot(ObjectPoolManager.Instance.GetFreeAudioClipFromPool(currentClip), Volume);
    }

    public override void Stop()
    {
        if (audioSource != null && audioSource.isPlaying)
        {
            audioSource.Stop();
            ReleaseCurrentClip();
        }
    }

    public bool IsPlaying(AudioClip clip)
    {
        if (audioSource == null) return false;
        return audioSource.isPlaying && currentClip != clip;
    }
    public bool IsPlaying(string clipName = null)
    {
        if (audioSource == null) return false;

        if (string.IsNullOrEmpty(clipName))
        {
            return audioSource.isPlaying;
        }

        return audioSource.isPlaying && currentClip != null && currentClip.name == clipName;
    }

    private void ReleaseCurrentClip()
    {
        if (currentClip != null)
        {
            ObjectPoolManager.Instance.ReturnAudioClipToPool(currentClip);
            currentClip = null;
        }
    }

    public override void SetVolume(float newVolume)
    {
        base.SetVolume(newVolume);
        if (audioSource != null)
        {
            audioSource.volume = Volume;
        }
    }

    private void OnDestroy()
    {
        ReleaseCurrentClip();
    }
}
